package apidocs;

import play.Play;
import play.data.validation.Validation;
import play.libs.Codec;
import play.libs.IO;
import play.mvc.Http;
import play.mvc.Scope;
import play.mvc.results.RenderTemplate;
import play.templates.BaseTemplate;
import play.templates.TemplateLoader;
import play.vfs.VirtualFile;

import java.io.File;
import java.util.Map;

/**
 * 模版工具
 *
 * @author zhangzc@djcars.cn
 * @create 2016/12/27
 */
public class TemplateUtil {


    /**
     * 渲染简单模版
     * @param templateContent 不支持标签，仅支持变量
     * @param args 变量表
     * @return
     */
    public static String renderAsGroovyTemplate(String templateContent, Map<String, Object> args){

        String key = Codec.hexMD5(templateContent);

        BaseTemplate template = TemplateLoader.load(key, templateContent);

        Scope.RenderArgs templateBinding = Scope.RenderArgs.current();
        templateBinding.data.putAll(args);
        templateBinding.put("session", Scope.Session.current());
        templateBinding.put("request", Http.Request.current());
        templateBinding.put("flash", Scope.Flash.current());
        templateBinding.put("params", Scope.Params.current());
        templateBinding.put("errors", Validation.errors());

        RenderTemplate rt =  new RenderTemplate(template, templateBinding.data);
        return rt.getContent();
    }
}
